package com.yueya.media.controller;

import com.yueya.common.base.BaseController;
import com.yueya.common.web.RestResult;
import com.yueya.media.model.MediaDto;
import com.yueya.media.service.MediaService;
import com.yueya.media.utils.Encodes;
import com.yueya.media.utils.FileUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * @author yueya
 */
@Controller
@RequestMapping(value = "${mds.admin.path}/medias")
public class MediaController extends BaseController {
    @Autowired
    private MediaService mediaService;

    @RequestMapping(value = {"download"}, method = RequestMethod.GET)
    public void download(String id, HttpServletRequest req, HttpServletResponse resp) {
        MediaDto gfile = mediaService.getMedia(id);
        try {
            if (gfile == null) {
                req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
                req.getRequestDispatcher("/WEB-INF/jsp/404.jsp").forward(req, resp);
                return;
            }
            try {
                resp.setContentType(FileUtils.getContentType(gfile.getName()));
                //设置Content-Disposition
                resp.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(gfile.getName()));
                ServletOutputStream ous = resp.getOutputStream();
                InputStream stream = mediaService.getInputStream(id);
                FileCopyUtils.copy(stream, ous);
                ous.flush();
                return;
            } catch (Exception e) {
                req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
                req.getRequestDispatcher("/WEB-INF/jsp/404.jsp").forward(req, resp);
                return;
            }
        } catch (Exception e) {
            logger.error("输出异常...");
        }
    }


    @ResponseBody
    @RequestMapping(value = "fileinfos", method = RequestMethod.GET)
    public List<MediaDto> files(String id) {
        return mediaService.findMediaList(id);
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    @ResponseBody
    public RestResult delete(String id) {
        try {
            mediaService.deleteById(id);
            return RestResult.OK("删除成功");
        } catch (Exception e) {
            logger.error("文件删除失败" + e.getMessage());
            return RestResult.ERROR("删除异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public RestResult upload(@RequestParam(value = "file", required = false) MultipartFile[] files, HttpServletRequest request) {
        //保存
        List<Map<String, Object>> ids = new ArrayList<>();
        Map<String, Object> parms = new HashedMap();
        Enumeration<String> enumeration = request.getParameterNames();
        String key;
        String keyFile = "file";
        while (enumeration.hasMoreElements()) {
            key = enumeration.nextElement();
            if (!keyFile.equals(key)) {
                parms.put(key, request.getParameter(key));
            }
        }
        try {
            if (files != null && files.length > 0) {
                //循环获取file数组中得文件  
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    String fileName = file.getOriginalFilename();
                    //保存文件
                    String id = mediaService.addNewMedia(fileName, file.getInputStream());
                    if (!parms.isEmpty()) {
                        mediaService.updateMeta(id, parms);
                    }
                    Map<String, Object> map = new HashedMap(2);
                    map.put("id", id);
                    map.put("name", fileName);
                    ids.add(map);
                }
                return RestResult.OkWithData(ids);
            }
        } catch (Exception e) {
            logger.error("上传异常",e);
            return RestResult.ERROR("上传异常");
        }
        return RestResult.ERROR("上传异常");
    }

}
